import { bitable } from "@lark-base-open/js-sdk";
import { Toast } from "@douyinfe/semi-ui";

let first_range_id = "";
export const commonInfo = {};
// 获取数据源
export function getDataSource() {
  return new Promise(async (resolve, reject) => {
    try {
      const { deepConfig, setConfig, formRef } = commonInfo;
      const tableList = await bitable.base.getTableMetaList();
      deepConfig.data_sorce = deepConfig.data_sorce || tableList?.[0]?.id;
      setConfig(deepConfig);
      formRef.current.formApi.setValue("data_sorce", deepConfig.data_sorce);
      changeSource(deepConfig.data_sorce);
      resolve(tableList);
    } catch (err) {
      Toast.error("获取数据源失败");
      reject(err);
    }
  });
}

// TODO 处理表头
export function initColumns() {
  // const { deepConfig, setConfig } = commonInfo;
  // deepConfig.show_columns = deepConfig.show_fields.map((item) => {
  //   return {
  //     title: item.name,
  //     type: "text", // 渲染icon
  //     dataIndex: "key",
  //     render: (text, record, index) => {
  //       return <div>{text}</div>;
  //     },
  //   };
  // });
  // console.log(deepConfig.show_columns);
  // setConfig(deepConfig);
  // TODO 测试代码
  return [
    {
      title: "标题",
      type: "text", // 渲染icon
      dataIndex: "key",
      render: (text, record, index) => {
        return <div>{text}</div>;
      },
    },
    {
      title: "文本",
      type: "text", // 渲染icon
      dataIndex: "key",
      render: (text, record, index) => {
        return <div>{text}</div>;
      },
    },
  ];
}

// TODO 获取数据
export function getDatas(table) {
  return new Promise(async (resolve, reject) => {
    const { data_range } = commonInfo.deepConfig;
    const recordList = await table.getRecords({
      pageSize: 5000,
      viewId: data_range === "all" ? undefined : data_range,
    });
    const data = [];
    const list = recordList?.records || [];
    for (let i = 0; i < list.length; i++) {
      const info = { key: Math.random() };
      const fields = list[i]?.fields;
      Object.keys(fields).forEach((key) => {
        const valueInfo = fields[key];
        if (!valueInfo) return;
        const value =
          valueInfo?.map?.((it) => it.text)?.join("，") ||
          valueInfo?.text ||
          valueInfo;
        info[key] = value;
      });
      if (Object.keys(info).length > 1) {
        data.push(info);
      }
    }
    console.log(data);
    resolve(data);
  });
}

// 处理滚动
let scrollTimer;
export function initScroll() {
  const { virtualizedListRef } = commonInfo;
  const { scroll_time, scroll_computed } = commonInfo.deepConfig;
  let scrollIndex = 0;
  clearInterval(scrollTimer);
  scrollTimer = setInterval(() => {
    scrollIndex += scroll_computed();
    virtualizedListRef.current?.scrollToItem(scrollIndex, "start");
  }, scroll_time * 1000);
}

// 拿到尺寸
export function getSize() {
  return new Promise((resolve) => {
    setTimeout(() => {
      const { line_computed } = commonInfo.deepConfig;
      const boxHeight = document.getElementById("app-box")?.offsetHeight;
      const yHeight = boxHeight - 38;
      resolve({
        x: "calc(100% - 340px)",
        y: yHeight,
        itemSize: yHeight / line_computed(),
      });
    }, 0);
  });
}

// 数据源改变，获取数据范围
export async function changeSource(value) {
  const { deepConfig, setConfig, formRef, setDataRange } = commonInfo;
  setDataRange([]);
  formRef.current.formApi.setValue("data_range", "all");
  deepConfig.data_sorce = value;
  setConfig(deepConfig);
  if (!value) return;
  try {
    const table = await bitable.base.getTable(value);
    const tables = await table.getViewMetaList();
    first_range_id = tables[0].id;
    setDataRange(tables);
    getAllFields("all", setConfig);
  } catch (err) {
    Toast.error("获取数据范围失败");
    console.log(err);
  }
}

// 重新拉取所有字段
export async function getAllFields(value) {
  const { deepConfig, setConfig } = commonInfo;
  deepConfig.data_range = value;
  setConfig(deepConfig);
  const { data_sorce, data_range } = deepConfig;
  if (!data_sorce || !data_range) return;
  const table = await bitable.base.getTable(data_sorce);
  const view = await table.getViewById(first_range_id);
  deepConfig.all_fields = await view.getFieldMetaList();
  deepConfig.show_fields.length = 0;
  for (let i = 0; i < 5; i++) {
    const item = deepConfig.all_fields?.[i];
    if (item) addField(item.id);
  }
  setConfig(deepConfig);
  getDatas(table);
  initColumns();
}

// 添加字段
export function addField(id) {
  const { deepConfig, setConfig } = commonInfo;
  const { all_fields, show_fields } = deepConfig;
  show_fields.push(
    JSON.parse(JSON.stringify(all_fields.find((item) => item.id === id)))
  );
  setConfig(deepConfig);
  initColumns();
}
